<template>
  <div class="radar-chart-container">
    <div class="chart-wrapper">
      <div class="analysis-button">
        <el-button 
          type="primary" 
          @click="exportChart"
          :loading="exportLoading"
          size="small"
          icon="el-icon-download"
        >
          导出图表
        </el-button>
        <el-button 
          type="primary" 
          @click="showAnalysis"
          :loading="analysisLoading"
          size="small"
        >
          数据分析
        </el-button>
      </div>
      <div ref="radarChart" class="radar-chart"></div>
    </div>
    
    <!-- 分析结果对话框 -->
    <el-dialog
      title="能力分析报告"
      :visible.sync="analysisDialogVisible"
      width="50%"
    >
      <div class="analysis-content">
        <div v-if="loading">数据加载中...</div>
        <div v-else-if="error">{{ error }}</div>
        <div v-else>
          <div class="report-header">
            <h3>学生能力分析报告</h3>
            <p>生成时间：{{ currentTime }}</p>
          </div>
          <div v-for="(item, index) in analysisResults" :key="index" class="result-item">
            <p :class="{'low-score': item.score < 60, 'high-score': item.score >= 60}">
              {{ item.message }}
            </p>
          </div>
          <div class="summary">
            <h4>总结建议：</h4>
            <p>{{ summaryAdvice }}</p>
          </div>
        </div>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="analysisDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="saveAnalysisReport">保存报告</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getStudentAbilityData, getStuWenti, getStujineng, getStushijian, getStusixiang, getzhishi } from '@/api/stuinfo/activity';

export default {
  name: 'StudentAbilityRadar',
  props: {
    studentId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      chart: null,
      studentData: null,
      loading: true,
      error: null,
      analysisLoading: false,
      analysisDialogVisible: false,
      exportLoading: false,
      analysisResults: [],
      currentTime: '',
      summaryAdvice: '',
      indicatorNames: ['知识掌握', '问题解决', '创新思维', '团队协作', '行为规范', '自主学习'],
      dimensionMap: {
        '知识掌握': '知识掌握',
        '问题解决': '问题解决',
        '创新思维': '创新思维',
        '团队协作': '团队协作',
        '行为规范': '沟通表达', // 前端显示"行为规范"，数据来自"沟通表达"
        '自主学习': '自主学习'
      },
      suggestions: {
        '知识掌握': '建议加强基础知识学习，定期复习课堂内容，多做练习题',
        '问题解决': '可以多做一些案例分析练习，培养逻辑思维能力',
        '创新思维': '参与更多创新实践活动，尝试不同的解决方案',
        '团队协作': '多参与小组项目活动，学习如何与他人合作',
        '行为规范': '建议遵守学校规章制度，注意日常行为举止，培养良好习惯',
        '自主学习': '制定个人学习计划，培养自主学习习惯'
      },
      exportOptions: {
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#fff'
      }
    };
  },
  mounted() {
    this.fetchStudentAbilityData();
    window.addEventListener('resize', this.handleResize);
    this.updateCurrentTime();
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    updateCurrentTime() {
      const now = new Date();
      this.currentTime = `${now.getFullYear()}年${now.getMonth()+1}月${now.getDate()}日 ${now.getHours()}时${now.getMinutes()}分`;
    },
    async fetchStudentAbilityData() {
      try {
        this.loading = true;
        const response = await getStudentAbilityData(this.studentId);
        const wenTi = await getStuWenti(this.studentId);
        const jineng = await getStujineng(this.studentId);
        const shijian = await getStushijian(this.studentId);
        const sixiang = await getStusixiang(this.studentId);
        const zhishi = await getzhishi(this.studentId);
        this.studentData = {
          name: '学生能力数据',
          scores: {
            知识掌握: zhishi.data,      
            问题解决: jineng.data,      
            创新思维: response.data, 
            团队协作: wenTi.data,     
            沟通表达: shijian.data,     
            自主学习: sixiang.data,   
          }
        };
      } catch (error) {
        this.error = '获取能力数据失败，请重试';
        console.error('获取数据失败:', error);
      } finally {
        this.loading = false;
        if (this.studentData) {
          this.initChart();
        }
      }
    },
    initChart() {
      this.chart = echarts.init(this.$refs.radarChart);
      this.updateChart();
    },
    updateChart() {
      if (!this.studentData) return;
      
      const { scores } = this.studentData;
      const studentScores = [
        scores.知识掌握,
        scores.问题解决,
        scores.创新思维,
        scores.团队协作,
        scores.沟通表达,
        scores.自主学习
      ];
      
      const option = {
        title: {
          text: '学生能力雷达图',
          left: 'center',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold',
            color: '#333'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            const indicator = this.indicatorNames[params.dataIndex];
            return `${indicator}：${params.value}`;
          }
        },
        radar: {
          indicator: this.indicatorNames.map(name => ({
            name,
            max: 100
          })),
          shape: 'polygon',
          splitNumber: 5,
          radius: '65%',
          axisName: {
            color: '#666',
            fontSize: 12
          },
          splitArea: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(0, 0, 0, 0.1)'
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(0, 0, 0, 0.1)'
            }
          }
        },
        series: [
          {
            name: '能力评估',
            type: 'radar',
            data: [
              {
                value: studentScores,
                name: '学生能力',
                symbol: 'circle',
                symbolSize: 6,
                lineStyle: {
                  width: 2,
                  color: '#007BFF'
                },
                areaStyle: {
                  color: 'rgba(0, 123, 255, 0.4)'
                },
                label: {
                  show: true,
                  formatter: '{c}'
                }
              }
            ]
          }
        ],
        color: ['#007BFF']
      };
      
      this.chart.setOption(option);
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    showAnalysis() {
      if (!this.studentData) {
        this.error = '请先加载数据';
        return;
      }
      this.analysisLoading = true;
      this.updateCurrentTime();
      this.generateAnalysisReport();
      this.analysisDialogVisible = true;
      this.analysisLoading = false;
    },
    generateAnalysisReport() {
      const { scores } = this.studentData;
      
      this.analysisResults = this.indicatorNames.map(name => {
        const dataField = this.dimensionMap[name];
        const score = scores[dataField] || 0;
        
        if (score < 60) {
          return {
            name,
            score,
            message: `${name} (${score}分): 有待提高。${this.suggestions[name]}`
          };
        } else {
          return {
            name,
            score,
            message: `${name} (${score}分): 表现良好，请继续努力！！`
          };
        }
      });

      // 生成总结建议
      const lowScores = this.analysisResults.filter(item => item.score < 60);
      if (lowScores.length > 0) {
        this.summaryAdvice = `您需要重点关注以下${lowScores.length}项能力：${lowScores.map(item => item.name).join('、')}。建议按照上述具体建议进行改进。`;
      } else {
        this.summaryAdvice = '您的各项能力表现均衡且优秀，继续保持当前学习状态！';
      }
    },
    saveAnalysisReport() {
      try {
        // 构建报告内容
        let reportContent = `学生能力分析报告\n`;
        reportContent += `生成时间: ${this.currentTime}\n\n`;
        
        reportContent += '各项能力评估:\n';
        this.analysisResults.forEach(item => {
          reportContent += `● ${item.message}\n`;
        });
        
        reportContent += '\n总结建议:\n';
        reportContent += this.summaryAdvice;
        
        // 创建文件名
        const fileName = `学生能力报告_${this.currentTime.replace(/[: ]/g, '-')}.txt`;
        
        // 创建Blob并下载
        const blob = new Blob([reportContent], { type: 'text/plain;charset=utf-8' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(link.href);
        
        this.$message.success(`报告已保存为 ${fileName}`);
      } catch (error) {
        console.error('保存报告失败:', error);
        this.$message.error('保存报告失败，请重试');
      }
    },
    exportChart() {
      if (!this.chart) {
        this.$message.error('图表尚未初始化');
        return;
      }
      
      this.exportLoading = true;
      
      try {
        // 获取图表的图片数据URL
        const chartImageURL = this.chart.getDataURL(this.exportOptions);
        
        // 创建下载链接
        const link = document.createElement('a');
        const fileName = `学生能力雷达图_${this.currentTime.replace(/[: ]/g, '-')}.${this.exportOptions.type}`;
        
        link.href = chartImageURL;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        this.$message.success('图表导出成功');
      } catch (error) {
        console.error('导出图表失败:', error);
        this.$message.error('图表导出失败，请重试');
      } finally {
        this.exportLoading = false;
      }
    }
  }
};
</script>

<style scoped>
.radar-chart-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: relative;
}

.chart-wrapper {
  position: relative;
  width: 100%;
  height: 500px;
}

.radar-chart {
  width: 100%;
  height: 100%;
  margin-top: 10px;
}

.analysis-button {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
  display: flex;
  gap: 10px;
}

.analysis-content {
  line-height: 1.8;
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 10px;
}

.report-header {
  text-align: center;
  margin-bottom: 20px;
}

.report-header h3 {
  color: #333;
  margin-bottom: 5px;
}

.report-header p {
  color: #666;
  font-size: 14px;
}

.result-item {
  margin-bottom: 12px;
  padding-left: 10px;
  border-left: 3px solid #eee;
}

.low-score {
  color: #F56C6C;
  font-weight: bold;
}

.high-score {
  color: #67C23A;
}

.summary {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.summary h4 {
  color: #333;
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>